package cn.concurrent;

import sun.misc.Unsafe;

/**
 *  模拟原子操作
 * @Author: lz
 * @Date: 2018/8/17 16:52
 * @Version 1.0
 */
public class AtomicBoolean implements java.io.Serializable {
	private static final long serialVersionUID = 4654671469794556979L;
	// setup to use Unsafe.compareAndSwapInt for updates
	private static final Unsafe unsafe = Unsafe.getUnsafe();
	private static final long valueOffset;

	static {
		try {
			valueOffset = unsafe.objectFieldOffset
					(AtomicBoolean.class.getDeclaredField("value"));
		} catch (Exception ex) { throw new Error(ex); }
	}

	private volatile int value;

	public final boolean get() {
		return value != 0;
	}

	public final boolean compareAndSet(boolean expect, boolean update) {
		int e = expect ? 1 : 0;
		int u = update ? 1 : 0;
		return unsafe.compareAndSwapInt(this, valueOffset, e, u);
	}

}